package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"user-mgmt-sys/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	var life = models.Life{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size
	var count int64
	var life []models.Life
	models.DB.Model(&life).Count(&count)
	err := models.DB.Offset(offset).Limit(size).Find(&life).Error
	if err != nil {

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"life":  life,
			"count": count,
		},
	})
	return
}
